package com.liuya.safe.util;

import com.liuya.common.StringUtil;
import com.liuya.db.DBPower;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 启动时初始化信息
 */
public class Startup {
    private static boolean started = false;

    /**
     * 初始化安装
     * @param datasourceDir
     * @param repositoryDir
     */
    public static void startup(String datasourceDir, String repositoryDir) {
        if (started) {
            return;
        }
        innerStart(datasourceDir, repositoryDir);
        started = true;
    }

    private static void innerStart(String datasourceDir, String repositoryDir) {
        datasourceDir = datasourceDir.trim();
        if (!datasourceDir.endsWith("/") && !datasourceDir.endsWith("\\")) {
            datasourceDir = datasourceDir + "/";
        }

        if (StringUtil.isEmpty(repositoryDir)) {
            repositoryDir = datasourceDir + "xml/";
        }
        repositoryDir = repositoryDir.trim();
        if (!repositoryDir.endsWith("/") && !repositoryDir.endsWith("\\")) {
            repositoryDir = repositoryDir + "/";
        }

        //设置数据源
        Map map = new HashMap();
        map.put(DBPower.BASE_CONFIG_DIR_MAP_KEY, datasourceDir);
        map.put(DBPower.DATASOURCES_CONFIG_FILE_MAP_KEY, "datasources.xml");
        DBPower.on(map);

        String businessDataStoreDir = repositoryDir + "policy/businessData/";
        String queryStoreDir = repositoryDir + "policy/query/";
        String userCategoryStoreDir = repositoryDir + "policy/userCategory/";
        String userTypeStoreDir = repositoryDir + "policy/userType/";

        new File(businessDataStoreDir).mkdirs();
        new File(queryStoreDir).mkdirs();
        new File(userCategoryStoreDir).mkdirs();
        new File(userTypeStoreDir).mkdirs();

        Constants.setRepositoryDir(repositoryDir);
        Constants.setBusinessDataStoreDir(businessDataStoreDir);
        Constants.setQueryStoreDir(queryStoreDir);
        Constants.setUserCategoryStoreDir(userCategoryStoreDir);
        Constants.setUserTypeStoreDir(userTypeStoreDir);
    }
}